import os
import re

def extract_test_cases_from_robot_file(file_path):
    """从robot framework文件中提取测试用例和标签"""
    test_cases = []
    current_test_case = None
    in_test_case_section = False
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
    except UnicodeDecodeError:
        # 如果UTF-8解码失败，尝试使用其他编码
        try:
            with open(file_path, 'r', encoding='latin-1') as f:
                content = f.read()
        except Exception as e:
            print(f"无法读取文件 {file_path}: {e}")
            return test_cases
    
    lines = content.split('\n')
    
    for line in lines:
        stripped_line = line.strip()
        
        # 检查是否进入测试用例部分
        if stripped_line == "*** Test Cases ***":
            in_test_case_section = True
            continue
        elif stripped_line.startswith("***") and in_test_case_section:
            in_test_case_section = False
            continue
            
        if not in_test_case_section:
            continue
            
        # 检查是否是测试用例名称行
        if (stripped_line and 
            not stripped_line.startswith('[') and 
            not stripped_line.startswith('#') and 
            not stripped_line.startswith('...') and
            current_test_case is None):
            current_test_case = stripped_line
            continue
            
        # 检查是否是标签行
        if current_test_case and '[Tags]' in stripped_line:
            # 提取标签部分
            tags_part = stripped_line.replace('[Tags]', '').strip()
            
            # 使用多种方式分割标签
            # 方法1: 使用多个空格分割
            tags = re.split(r'\s{2,}', tags_part)
            
            # 方法2: 如果方法1没有结果，尝试使用单个空格分割
            if len(tags) == 1 and tags[0] == tags_part:
                tags = tags_part.split()
                
            # 方法3: 如果仍然没有结果，尝试使用制表符分割
            if len(tags) == 1 and tags[0] == tags_part:
                tags = tags_part.split('\t')
                
            # 过滤并添加Get_开头的标签
            for tag in tags:
                tag = tag.strip()
                if tag and tag.startswith("Get_"):
                    test_cases.append({
                        "name": current_test_case,
                        "tag": tag
                    })
            
            # 重置当前测试用例
            current_test_case = None
    
    print(f"从文件 {file_path} 中提取到 {len(test_cases)} 个测试用例")
    return test_cases

def generate_component_ci_file(directory_structure, output_file="../test_lists/COMP_CI"):
    """生成COMP_CI文件"""
    component_mapping = {
        "1_cli": "验证cli命令",
        "2_web": "验证web命令",
        "3_redfish": "验证redfish命令",
        "4_ipmi": "验证ipmi命令"
    }

    with open(output_file, 'w', encoding='utf-8') as f:
        for folder, comment in component_mapping.items():
            if folder in directory_structure and directory_structure[folder]:
                f.write(f"# {comment}\n")
                for test_case in directory_structure[folder]:
                    f.write(f"--include {test_case['tag']}\n")
                f.write("\n")
            else:
                print(f"目录 {folder} 中没有找到测试用例")

def main():
    base_dir = "../test_cases"
    
    # 定义目录结构
    directories = {
        "1_cli": [],
        "2_web": [],
        "3_redfish": [],
        "4_ipmi": []
    }

    # 遍历所有目录和文件
    for folder in directories.keys():
        folder_path = os.path.join(base_dir, folder)
        if os.path.exists(folder_path):
            for file in os.listdir(folder_path):
                if file.endswith(".robot"):
                    file_path = os.path.join(folder_path, file)
                    test_cases = extract_test_cases_from_robot_file(file_path)
                    directories[folder].extend(test_cases)
        else:
            print(f"目录不存在: {folder_path}")
    
    # 生成COMP_CI文件
    generate_component_ci_file(directories)
    print("COMP_CI文件已生成!")
    
    # 打印统计信息
    total_cases = sum(len(cases) for cases in directories.values())
    print(f"总共找到 {total_cases} 个测试用例")

if __name__ == "__main__":
    main()